/*
 * @Author: your name
 * @Date: 2020-02-27 15:28:43
 * @LastEditors: komons
 * @LastEditTime: 2020-03-04 17:01:16
 * @Description: 获取账单类型
 * @FilePath: \form-builderc:\Komons\学习\visualization\src\utils\api\billApi.js
 */
import config from "src/config";
import axios from "axios";
import {
  getToLocalstorage,
  saveToSessionStorage,
  getToSessionStorage
} from "../storageUtils";

function initAxios() {
  let token = getToLocalstorage("token");
  const instance = axios.create({
    timeout: 1000,
    headers: { "x-jwt-token": token }
  });
  return instance;
}

export const getTypes = () => {
  const url = config.api + "/bill/getType";
  return new Promise((resolve, reject) => {
    let billTypes = getToSessionStorage("bill_types");
    if (billTypes) {
      resolve(billTypes);
    } else {
      initAxios()
        .get(url)
        .then(data => {
          resolve(data.data);
          saveToSessionStorage("bill_types", data.data);
        })
        .catch(err => {
          reject(err);
        });
    }
  });
};

export const addBill = ({ date, money, type, isIncome, desc }) => {
  const url = config.api + "/bill/add";
  return new Promise((resolve, reject) => {
    initAxios()
      .post(url, {
        price: money,
        classid: type,
        income: isIncome,
        mark: desc,
        date
      })
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err);
      });
  });
};

export const getBillList = params => {
  const url = config.api + "/bill/get";
  return new Promise((resolve, reject) => {
    initAxios()
      .get(url, {
        params
      })
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err);
      });
  });
};
